﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using TaskToLineUp;
using ETLDispatcher;
using EtlComm;
using ETLHandler;
using StructureMap;
using System.Net;
using System.ServiceModel;
using System.Diagnostics;
using System.Data;
using System.Runtime.InteropServices;
using System.Configuration;

namespace EtlConsol
{
    class Program
    {
        public delegate bool ConsoleCtrlDelegate(int dwCtrlType);

        [DllImport("user32.dll", EntryPoint = "FindWindow")]
        extern static IntPtr FindWindow(string lpClassName, string lpWindowName);
        [DllImport("user32.dll", EntryPoint = "GetSystemMenu")]
        extern static IntPtr GetSystemMenu(IntPtr hWnd, IntPtr bRevert);
        [DllImport("user32.dll", EntryPoint = "RemoveMenu")]
        extern static IntPtr RemoveMenu(IntPtr hMenu, uint uPosition, uint uFlags);
        [DllImport("kernel32.dll")]
        static extern bool SetConsoleCtrlHandler(ConsoleCtrlDelegate HandlerRoutine, bool Add);
       
        private static IEDTDispatcher TaskDispatcher;
        //关闭按钮
        private const int CTRL_CLOSE_EVENT = 2;


        static void Main(string[] args)
        {
            if (args.Length <= 0)
                return;
            if (args[0] != "96e65773803e47ee1001b05a99965d76")
                return;
            //不能捕获的异常处理
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionEventHandler);
            AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);
            ConsoleCtrlDelegate newDelegate = new ConsoleCtrlDelegate(HandlerRoutine);
            bool bRet = SetConsoleCtrlHandler(newDelegate, true);
#if TRIAL
            if (DateTime.Now >= new DateTime(2013, 4, 1))
            {
                Console.WriteLine("试用软件已经到期...");
                Console.ReadKey();
                return;
            }
#endif
#if TRIAL
            Console.Title = "中国石油数据服务运行中......(试用版)";
#else
            Console.Title = "中国石油数据服务运行中......";
#endif

            Console.ForegroundColor = ConsoleColor.Yellow;

            EtlGlobal.Initialize();

            bool createnew;
            Mutex mutex = new Mutex(true, "sunsjw@foxmail.com", out createnew);
            if (createnew)
            {
                Console.WriteLine("China Petroleum Data Services Running......");
                Thread.Sleep(1000);
            }
            else
            {
                Console.WriteLine("China Petroleum Data Services has been running......\r\nProgram will exit after two seconds.");
                Thread.Sleep(2000);
                Environment.Exit(0);
            }
            ObjectFactory.Initialize(x =>
            {
                //x.UseDefaultStructureMapConfigFile = true;
                x.PullConfigurationFromAppConfig = true;
            });

            //Thread t = new Thread(new ThreadStart(LoadWcfService));
            //t.Name = "thread:WcfServices";
            //t.Start();
            Thread t2 = new Thread(new ThreadStart(ShowEtlStatus));
            t2.Name = "thread:ShowEtlStatus";
            t2.Start();

            try
            {
                //获取任务列表
                IList<StationObject> lstSO = TaskQueuer.StationObjectList;
                TaskDispatcher = new EtlDispatcher();
                TaskDispatcher.log = LogFactory.CreateLog<ServiceBaseLog>();
                TaskDispatcher.Active = true;
                //调度任务
                TaskDispatcher.Initialize(lstSO);
                TaskDispatcher.Run();
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            while (true)
            {
                string quit = Console.ReadLine();
                if (quit.Equals("exit", StringComparison.CurrentCultureIgnoreCase))
                {
                    EtlGlobal.IsTerminated = true;
                    TaskDispatcher.Active = false;
                    Environment.Exit(0);
                    break;
                }
            }
        }

        static void CurrentDomain_ProcessExit(object sender, EventArgs e)
        {
            if (e == null)
            {
                e = new EventArgs();
            }
            Console.WriteLine(e.ToString() + " System exiting...");
            EtlGlobal.IsTerminated = true;
            Debug.Assert(TaskDispatcher != null);
            TaskDispatcher.Active = false;
            if (!TaskDispatcher.Stop())
                Console.WriteLine("保存系统状态时出错，下次启动需要手动更新数据...");
            Thread.Sleep(1000);

        }

        private static void ShowEtlStatus()
        {
           
            DateTime dtBegin = DateTime.Now;
        begin:
            Console.WriteLine(Environment.NewLine);
            Console.WriteLine(Environment.NewLine);
            Console.WriteLine(Environment.NewLine);
            Console.WriteLine("\t|------------中国石油加油站数据服务运行中-----------|");
            Console.WriteLine("\t|\t\t\t\t\t\t\t|");
            Console.WriteLine("\t|\t\t\t\t\t\t\t|");
            Console.WriteLine("\t|\t\t\t\t\t\t\t|");
            Console.WriteLine(string.Format("\t|\t\t启动时间：{0}\t\t|", dtBegin));
            Console.WriteLine("\t|\t\t\t\t\t\t\t|");
            Console.WriteLine(string.Format("\t|\t\t运行时间：{0}\t\t|", DateTime.Now - dtBegin));
            Console.WriteLine("\t|\t\t\t\t\t\t\t|");
            Console.WriteLine("\t|\t\t\t\t\t\t\t|");
            Console.WriteLine("\t|-------------------------------------------------------|");
            Console.WriteLine(Environment.NewLine);
            Console.WriteLine(Environment.NewLine);
            Console.WriteLine(Environment.NewLine);
#if TRIAL
            Console.WriteLine("\t\tCopyright ©成都微讯威软件有限公司 试用版本 2013-4-1到期");
#else
            Console.WriteLine("\t\tCopyright ©成都微讯威软件有限公司");
#endif
            Console.WriteLine("\t\t\t\t 维护电话：18980999866 QQ:509216023");

            Thread.Sleep(1000);
            Console.Clear();
            if(!EtlGlobal.IsTerminated)
                goto begin;
        }

        private static void LoadWcfService()
        {
            try
            {
                ServiceHost host = new ServiceHost(typeof(EtlContract.WCFEtlServices));
                host.Open();
                Debug.WriteLine(host.BaseAddresses.First().OriginalString);
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        static void UnhandledExceptionEventHandler(object sender, UnhandledExceptionEventArgs e)
        {
            //EtlGlobal.IsTerminated = true;
            //Console.WriteLine("----unknown error:" + e.ExceptionObject);
            Environment.Exit(-5);
        }
        //移除控制栏
        static void RemoveCloseBtn()
        {
#if TRIAL
            IntPtr windowHandle = FindWindow(null, "中国石油数据服务运行中......(试用版)");
#else
            IntPtr windowHandle = FindWindow(null, "中国石油数据服务运行中......");
#endif
            IntPtr closeMenu = GetSystemMenu(windowHandle, IntPtr.Zero);
            uint SC_CLOSE = 0xF060;
            RemoveMenu(closeMenu, SC_CLOSE, 0x0);
        }
        //窗口关闭处理
        private static bool HandlerRoutine(int CtrlType)
        {
            switch (CtrlType)
            {
                case CTRL_CLOSE_EVENT: //用户要关闭Console了
                    CurrentDomain_ProcessExit(null, null);
                    break;
            }
            return true;
        }

    }
}
